﻿using FakeXiecheng.API.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using System.Reflection;
using System.Text.Json.Serialization;

namespace FakeXiecheng.API.Database
{
    public class AppDbContext : IdentityDbContext<IdentityUser>
    {

        public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
        {
        }

        // 实体类对应的表
        public DbSet<TouristRoute> TouristRoutes { get; set; }
        public DbSet<TouristRoutePicture> TouristRoutePictures { get; set; }




        //使用modelBuilder来添加种子数据
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            //hasData 用来提供模型的数据支持
            /* 
             * 
             * 通过自定义数据这样的方式添加数据，很慢，代码复杂，所以舍弃，我们通过外部文件的方式进行
             * 数据库中种子数据的添加
             * 
             * modelBuilder.Entity<TouristRoute>().HasData(new TouristRoute()
             {
                 Id = Guid.NewGuid(),
                 Title = "ceshititle",
                 Description = "shuoming",
                 OriginalPrice = 0,
                 CreateTime = DateTime.UtcNow
             });*/

            var touristRouteJsonData = File.ReadAllText(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + @"/Database/touristRoutesMockData.json");
            IList<TouristRoute> touristRoutes = JsonConvert.DeserializeObject<IList<TouristRoute>>(touristRouteJsonData);
            modelBuilder.Entity<TouristRoute>().HasData(touristRoutes);

            var TouristRoutePictureJsonData = File.ReadAllText(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + @"/Database/touristRoutePicturesMockData.json");
            IList<TouristRoutePicture> TouristRoutePictures = JsonConvert.DeserializeObject<IList<TouristRoutePicture>>(TouristRoutePictureJsonData);
            modelBuilder.Entity<TouristRoutePicture>().HasData(TouristRoutePictures);

            base.OnModelCreating(modelBuilder);

        }

    }
}
